package com.cjh.controller;


import com.cjh.constant.JwtConstant;
import com.cjh.entity.User;
import com.cjh.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author cjh
 * @since 2021-04-23
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @GetMapping
    public User get(){
        return userService.getNickName();
    }

    @PostMapping("/home")
    public String home(){
        return "home";
    }

    @GetMapping("test1")
    @PreAuthorize("hasAuthority('sys:add')")
    public String test1() {
        return "add成功";
    }


    @GetMapping("test2")
    @PreAuthorize("hasAuthority('sys:delete')")
    public String test2() {
        return "delete成功";
    }

    /**
     * 登出的接口
     * 把redis里面的token删掉就搞定了
     *
     * @return
     */
    @PostMapping("myLogout")
    public String logout(HttpServletRequest request) {
        // 拿到token 从request拿 因为每次请求都会从header里面带进来
        String header = request.getHeader(JwtConstant.AUTHORIZATION);
        if (StringUtils.hasText(header)) {
            String jwt = header.replaceAll("bearer ", "");
            if (StringUtils.hasText(jwt)) {
                // 删掉redis
                redisTemplate.delete(JwtConstant.JWT_PREFIX + jwt);
            }
        }
        return "登出成功";
    }

}

